package cn.flyingroc.travelbook;

import java.util.ArrayList;



import cn.flyingroc.travelbook.model.POI;
import cn.flyingroc.travelbook.util.DatabaseHelper;


import android.app.Activity;
import android.app.AlertDialog;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;

import android.widget.ListView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnCreateContextMenuListener; 

public class MyPOIList extends Activity {
	
	private static final String LOG_TAG = "MyPOIList";
	private static final int MENU_NEW_MYPOI = Menu.FIRST + 1;
    private static final int MENU_REFRESH_MYPOI = Menu.FIRST + 2;
    private static final int MENU_MANAGEMENT_MYPOI = Menu.FIRST + 3;
    public static final int COMPOSE_UPDATE_REQUEST_CODE = 1339;
    private DatabaseHelper databaseHelper;
	private SQLiteDatabase sqliteDatabase;
    Context context;
    private ListView list;
    private ArrayList<POI> poilist;
    private ProgressDialog progressDialog = null;
    private Handler handler = new Handler();
    public static final String KEY_ROWID = "ID";
    
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mypois);
		
		context = getApplicationContext();
		this.open(context);
		
		
		list = (ListView) findViewById(R.id.poilist);
		registerForContextMenu(list);
		
		showList();
		
		
		//长按菜单事件
		list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View arg1,
					ContextMenuInfo arg2) {
				// TODO Auto-generated method stub
				menu.setHeaderTitle("管理兴趣点");
				menu.add(0, 0, 0, "删除");
			}
		});
		
		list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Log.i(LOG_TAG, "done!");
			}
			
		});
		
	}
	
	
	/**
     * 打开数据库连接 
     */
    public void open(Context context)  
    {  
        databaseHelper = new DatabaseHelper(context);  
        
        try  
        {
            sqliteDatabase = databaseHelper.getWritableDatabase();  
        }catch(SQLiteException ex)  
        {
            sqliteDatabase = databaseHelper.getReadableDatabase();  
        }  
    }
    
	public boolean onContextItemSelected(MenuItem item) {
		
		try {
			final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
			if (item.getItemId()==0&&item.getGroupId()==0&&item.getOrder()==0){//删除按钮
				new AlertDialog.Builder(this)
		         .setTitle("提示")
		         .setMessage("确定删除?")
		         .setIcon(R.drawable.quit)
		         .setPositiveButton("确定", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		        	deleteUpdate(poilist.get(info.position));
		            poilist.remove(info.position);
		            updateList();
		            Main.mMakeTextToast(context, "删除完成", false);
		         }
		         })
		         .setNegativeButton("取消", new DialogInterface.OnClickListener() {
		        	 public void onClick(DialogInterface dialog, int whichButton) {
		        		 //取消按钮事件
		        	 }
		         })
		         .show(); 
				
			}
            
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return super.onContextItemSelected(item);
	}
	
	private void deleteUpdate(POI poi) {
		// TODO Auto-generated method stub
		//db.execSQL("delete from TravelBook where id = "+poi.id);
		sqliteDatabase.delete(DatabaseHelper.DATABASE_TABLE,KEY_ROWID +"="+poi.id , null);
	}

	private void showList() {
		progressDialog = ProgressDialog.show(MyPOIList.this, "请稍等...", "获取兴趣点列表...", true); 
		new Thread() {
            public void run() {
                try {
                	poilist = getPOIList();
                    if (poilist != null && poilist.size() > 0)
                        updateList();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                progressDialog.dismiss();
            }
            
        }.start();
	}
	
	protected ArrayList<POI> getPOIList() {
		ArrayList<POI> ret = new ArrayList<POI>();
		
		Cursor cur = sqliteDatabase.query("MYPOI", new String[] { "ID", "TITLE","DESC","LAT","LON","PHOTONAME","CREATETIME"}, null, null, null, null, null);
		cur.moveToFirst();
		POI poi = null;
	    while (!cur.isAfterLast()) {
	    	poi = new POI();
	    	poi.id = cur.getInt(0);
	    	poi.title = cur.getString(1);
	    	poi.desc = cur.getString(2);
	    	poi.lat = cur.getDouble(3);
	    	poi.lon = cur.getDouble(4);
	    	poi.photoName = cur.getString(5);
	    	poi.createdTime = cur.getString(6);
	    	ret.add(poi);
	        cur.moveToNext();
	    }
		cur.close();
		return ret;
	}

	private void updateList() {
		// TODO Auto-generated method stub
		handler.post(new Runnable() {
            public void run() {
                list.setAdapter(new UpdateAdapter(MyPOIList.this, poilist));
            }
        });
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
        menu.add(0, MENU_NEW_MYPOI, 0, "创建新兴趣点")
                .setIcon(R.drawable.twitter)
                .setAlphabeticShortcut('N');
        menu.add(0, MENU_REFRESH_MYPOI, 0, "刷新")
                .setIcon(R.drawable.refresh)
                .setAlphabeticShortcut('R');
        menu.add(0, MENU_MANAGEMENT_MYPOI, 0, "管理我的兴趣点")
                .setIcon(R.drawable.message)
                .setAlphabeticShortcut('M');
        
        return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
	        case MENU_NEW_MYPOI: {
	            Intent i = new Intent(MyPOIList.this, NewPOI.class);
	            startActivityForResult(i, COMPOSE_UPDATE_REQUEST_CODE);
	            finish();
	            return true;
	        }
	        case MENU_REFRESH_MYPOI: {
	            //getUpdates();
	            return true;
	        }
	        case MENU_MANAGEMENT_MYPOI: {
	            //Intent i = new Intent(TwitterList.this, Messages.class);
	            //startActivity(i);
	            return true;
	        }
	        
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
    	//按下键盘上返回按钮
    	if(keyCode == KeyEvent.KEYCODE_BACK){
    		 new AlertDialog.Builder(this).setIcon(R.drawable.bookmark).setTitle(R.string.prompt)
    		 .setMessage(R.string.quit_desc)
    		 .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
	    		 @Override
	    		 public void onClick(DialogInterface dialog, int which) {
	    			 
	    		 }
    		 })
    		 .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
	    		 public void onClick(DialogInterface dialog, int whichButton) {
	    			 finish();
	    			 android.os.Process.killProcess(android.os.Process.myPid());
	    			 //System.exit(0);
	    		 }
    		 }).show();
    		 	return true;
    	}else{
    		return super.onKeyDown(keyCode, event);
    	}
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}
	
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (sqliteDatabase.isOpen()){
			sqliteDatabase.close();
		}
		//System.exit(0);
		//或者下面这种方式
		//android.os.Process.killProcess(android.os.Process.myPid());
	}
	
}
